# 识别古诗文网登录验证码 https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx

import base64
import json
import os

import requests
from lxml import etree


def base64_api(uname, pwd, img):
    with open(img, 'rb') as f:
        base64_data = base64.b64encode(f.read())
        b64 = base64_data.decode()
    data = {"username": uname, "password": pwd, "image": b64}
    result = json.loads(requests.post("http://api.ttshitu.com/base64", json=data).text)
    if result['success']:
        return result["data"]["result"]
    else:
        return result["message"]
    return ""


# if __name__ == "__main__":
#     img_path = "C:/Users/Administrator/Desktop/file.jpg"
#     result = base64_api(uname='你的账号', pwd='你的密码', img=img_path)
#     print(result)

if __name__ == '__main__':
    # 爬取到页面源码数据
    url = 'https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx'
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.3'}
    page_text = requests.get(url=url, headers=headers).text
    if not os.path.exists('./codepic'):
        os.makedirs('./codepic')
    # 数据解析
    tree = etree.HTML(page_text)
    code_img_src = 'https://so.gushiwen.cn/' + tree.xpath('//*[@id="imgCode"]/@src')[0]
    img_data = requests.get(url=code_img_src, headers=headers).content
    img_name = 'imgCode' + '.jpg'
    print(code_img_src, img_name)
    # 将图片保存到了本地
    img_path = 'codepic/' + img_name
    with open(img_path, 'wb') as fp:
        fp.write(img_data)
        print(img_name, '下载成功')
    code = base64_api('xxx', 'xxx', img_path)
    print('验证码是：', code)
